<?php

class Controller_Admin extends Controller_Action
{
	/**
	 *
	 * @var XmlService
	 */
	private $xmlService;
	/**
	 *
	 * @var VendorService
	 */
	private $vendorService;
	
	/**
	 * @return VendorService
	 */
	public function getVendorService() {
		if (!$this->vendorService) {
			$this->vendorService = VendorService::getInstance();
		}
		return $this->vendorService;
	}
	
	/**
	 * @return XmlService
	 */
	public function getXmlService() {
		if (!$this->xmlService) {
			$this->xmlService = XmlService::getInstance();
		}
		return $this->xmlService;
	}
	public function preDispatch()
	{
		parent::preDispatch();
		$this->view->menu = $this->_getCurModuleMenu();
	}
	
	
	/**
	 * Returns menu items of the current modules scanning PHP files.
	 * For current controller also fills actions list.
	 *
	 * @return array  Resulting menu
	 */
	private function _getCurModuleMenu()
	{
		$menu = array();
		$class = new ReflectionClass(get_class($this));
		foreach (glob(dirname($class->getFileName()) . "/*.php") as $fn) {
			if (preg_match('/^(.*)Controller\..*$/s', basename($fn), $m)) {
				$controller = implode('-', array_map('strtolower', preg_split( '/([A-Z][a-z]*)/', $m[1], -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)));
				//$controller = strtolower($m[1]);
				$isCurrentController = basename($fn) == basename($class->getFileName()); 
				$actions = array();
				if ($isCurrentController) {
					foreach ($class->getMethods() as $method) {
						if (preg_match('/^([^_]*)(?<!Edit|View)Action$/is', $method->getName(), $p)) {
							$action = strtolower($p[1]);
							$actions[] = array(
								'name' => $action,
								'url' => u(array("controller" => $controller, "action" => $action)),
								'current' => $action == $this->getRequest()->getActionName()
							);
						}
					}
				}
				
				$menu[] = array(
					'name' => $controller,
					'url' => u(array("controller" => $controller, "action" => "index")),
					'current' => $isCurrentController,
					'menu' => $actions
				);
			}
		}
		return $menu;
	}
}